package com.hulk.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 属性文件*.properties工具类
 * 
 * @author csatl
 * 
 */
public class PropertiesUtil {

	/**
	 * 获取属性文件
	 * 
	 * @param classPath：类路径
	 * @return
	 * @throws Exception
	 */
	public static Properties getByClassPath(String classPath) throws Exception {
		InputStream in;
		try {
			in = ClassLoaderUtil.getExtendResource(classPath).openStream();
			return getByInputStream(in);
		} catch (Exception e) {
			throw new Exception("属性文件读取失败：" + classPath);
		}
	}

	/**
	 * 获取属性文件
	 * 
	 * @param absolutePath：绝对路径
	 * @return
	 * @throws Exception
	 */
	public static Properties getByAbsolutePath(String absolutePath) throws Exception {
		InputStream in;
		try {
			in = new BufferedInputStream(new FileInputStream(absolutePath));
			return getByInputStream(in);
		} catch (Exception e) {
			throw new Exception("属性文件读取失败：" + absolutePath);
		}
	}

	/**
	 * 获取属性文件
	 * 
	 * @param in：输入流
	 * @return
	 * @throws Exception
	 */
	public static Properties getByInputStream(InputStream in) throws Exception {
		if (in != null) {
			try {
				Properties props = new Properties();
				props.load(in);
				return props;
			} catch (IOException e) {
				throw new Exception(e);
			} finally {
				try {
					in.close();
				} catch (IOException e) {
					throw new Exception(e);
				}
			}
		} else {
			throw new Exception("InputStream为空");
		}
	}

	/**
	 * main方法
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		System.out.println(getByClassPath("scp.properties"));
		System.out.println(getByAbsolutePath("D:/360云盘/我的项目/quick/src/quick.properties"));
	}

}
